import File from '../util/File.js'
import { Router } from 'express'
import busboy from 'busboy'
import path from 'path'
import fs from 'fs'
import { randomFillSync } from 'crypto'

//删除头像图timer
let head_img_timers = new Map()
//删除微头条封面图timer
let min_article_files_timers = new Map()
//删除文章封面图timer
let cover_img_timers = new Map()
//删除文章内容图timer
let article_img_timers = new Map()
//删除文章内容视频timer
let article_video_timers = new Map()

//随机生成文件名
const random = (() => {
    const buf = Buffer.alloc(16)
    return () => randomFillSync(buf).toString('hex')
})()

let router = Router()

//上传头像
router.post('/api/head_img', (req, res) => {
    //随机文件名
    let file_url = `/assets/img/${ random() }`

    const bb = busboy({ headers: req.headers })

    bb.on('file', (name, file, info) => {
        //获取文件路径
        let reg = info.filename.match(/\.(\w+)$/)
        let file_suffix = reg[0]
        file_url += file_suffix

        //本地文件路径
        const saveTo = path.join(path.resolve(), 'public', file_url)
        file.pipe(fs.createWriteStream(saveTo))

        //在session上保持本地文件路径
        req.session.head_imgs.push(saveTo)

        //下次上传新文件时清除上次timer
        if ( head_img_timers.get(req.sessionID) ) {
            clearTimeout(head_img_timers.get(req.sessionID))
            head_img_timers.delete(req.sessionID)
        }

        //设置一个小时后删除临时文件timer
        let timer = setTimeout(() => {
            File.delete(req.session.head_imgs)
            req.session.head_imgs = []
        }, 60 * 60 * 1000)
        head_img_timers.set(req.sessionID, timer)

    })

    bb.on('close', () => {
        //返回网络文件路径
        res.end(JSON.stringify({ code: 200, data: 'http://127.0.0.1:3000' + file_url }))
    })

    req.pipe(bb)
})

//微头条封面图
router.post('/api/min_article_files', (req, res) => {
    //随机文件名
    let file_url = `/assets/img/${ random() }`

    const bb = busboy({ headers: req.headers })

    bb.on('file', (name, file, info) => {
        //获取文件路径
        let reg = info.filename.match(/\.(\w+)$/)
        let file_suffix = reg[0]
        file_url += file_suffix

        //本地文件路径
        const saveTo = path.join(path.resolve(), 'public', file_url)
        file.pipe(fs.createWriteStream(saveTo))

        //在session上保持本地文件路径
        req.session.min_article_files.push(saveTo)

        //下次上传新文件时清除上次timer
        if ( min_article_files_timers.get(req.sessionID) ) {
            clearTimeout(min_article_files_timers.get(req.sessionID))
            min_article_files_timers.delete(req.sessionID)
        }

        //设置三个小时后删除临时文件timer
        let timer = setTimeout(() => {
            File.delete(req.session.min_article_files)
            req.session.min_article_files = []
        }, 3 * 60 * 60 * 1000)
        min_article_files_timers.set(req.sessionID, timer)
    })

    bb.on('close', () => {
        //返回网络文件路径
        res.end(JSON.stringify({ code: 200, data: 'http://127.0.0.1:3000' + file_url }))
    })

    req.pipe(bb)
})

//文章封面图
router.post('/api/cover_img', (req, res) => {
    //随机文件名
    let file_url = `/assets/img/${ random() }`

    const bb = busboy({ headers: req.headers })

    bb.on('file', (name, file, info) => {
        //获取文件路径
        let reg = info.filename.match(/\.(\w+)$/)
        let file_suffix = reg[0]
        file_url += file_suffix

        //本地文件路径
        const saveTo = path.join(path.resolve(), 'public', file_url)
        file.pipe(fs.createWriteStream(saveTo))

        //在session上保持本地文件路径
        req.session.cover_imgs.push(saveTo)

        //下次上传新文件时清除上次timer
        if ( cover_img_timers.get(req.sessionID) ) {
            clearTimeout(cover_img_timers.get(req.sessionID))
            cover_img_timers.delete(req.sessionID)
        }

        //设置三个小时后删除临时文件timer
        let timer = setTimeout(() => {
            File.delete(req.session.cover_imgs)
            req.session.cover_imgs = []
        }, 3 * 60 * 60 * 1000)
        cover_img_timers.set(req.sessionID, timer)

    })

    bb.on('close', () => {
        //返回网络文件路径
        res.end(JSON.stringify({ code: 200, data: 'http://127.0.0.1:3000' + file_url }))
    })

    req.pipe(bb)
})

//文章内容图
router.post('/api/article_img', (req, res) => {
    let file_url = `/assets/img/${ random() }`

    const bb = busboy({ headers: req.headers })

    bb.on('file', (name, file, info) => {
        //获取文件路径
        let reg = info.filename.match(/\.(\w+)$/)
        let file_suffix = reg[0]
        file_url += file_suffix

        //本地文件路径
        const saveTo = path.join(path.resolve(), 'public', file_url)
        file.pipe(fs.createWriteStream(saveTo))

        //在session上保持本地文件路径
        req.session.article_imgs.push(saveTo)

        //下次上传新文件时清除上次timer
        if ( article_img_timers.get(req.sessionID) ) {
            clearTimeout(article_img_timers.get(req.sessionID))
            article_img_timers.delete(req.sessionID)
        }

        //设置三个小时后删除临时文件timer
        let timer = setTimeout(() => {
            File.delete(req.session.article_imgs)
            req.session.article_imgs = []
        }, 3 * 60 * 60 * 1000)
        article_img_timers.set(req.sessionID, timer)
        
    })

    bb.on('close', () => {
        //返回网络文件路径
        res.end( JSON.stringify({ 
            errno: 0,
            data: {
                url: 'http://127.0.0.1:3000' + file_url,
            }
        }) )
    })

    req.pipe(bb)
})

//文章内容视频
router.post('/api/article_video', (req, res) => {
    let file_url = `/assets/video/${ random() }`

    const bb = busboy({ headers: req.headers })

    bb.on('file', (name, file, info) => {
        //获取文件路径
        let reg = info.filename.match(/\.(\w+)$/)
        let file_suffix = reg[0]
        file_url += file_suffix

        //本地文件路径
        const saveTo = path.join(path.resolve(), 'public', file_url)
        file.pipe(fs.createWriteStream(saveTo))

        //在session上保持本地文件路径
        req.session.article_videos.push(saveTo)

        //下次上传新文件时清除上次timer
        if ( article_video_timers.get(req.sessionID) ) {
            clearTimeout(article_video_timers.get(req.sessionID))
            article_video_timers.delete(req.sessionID)
        }

        //设置三个小时后删除临时文件timer
        let timer = setTimeout(() => {
            File.delete(req.session.article_videos)
            req.session.article_videos = []
        }, 3 * 60 * 60 * 1000)
        article_video_timers.set(req.sessionID, timer)

    })

    bb.on('close', () => {
        //返回网络文件路径
        res.end( JSON.stringify({ 
            errno: 0,
            data: {
                url: 'http://127.0.0.1:3000' + file_url,
            }
        }) )
    })

    req.pipe(bb)
})

export default router